import sys

import yaml
from ultralytics import YOLO

import logo.Mlog
from dataTemp.prop import Prop
from event import event


def loadYaml():
    # 读取YAML文件
    # 使用 pkg_resources 获取资源文件的路径
    with open('./Detection.yaml', 'r', encoding='utf-8') as file:
        try:
            config = yaml.safe_load(file)
            # print(config)
            return config["names"]
        except yaml.YAMLError as e:
            print(e)


names = loadYaml()
# print(names)
enemy: [str] = ["投弹兵", "哥布林", "狮子手上", "冰精灵", "邪恶娃娃", "光头娃娃", "班图女战士", "布万家Boss", "班图蛇",
                "狮子手下", "狮子头", "班图高战士", "班图兔战士女", "班图兔战士男", "哥布林", "投弹兵"]
stuff: [str] = ["金币", "炉岩碳", "魔力结晶", "白装备", "紫装备", "粉装备", "蓝色装备"]
ico: [str] = ["加载过渡", "通关","返回城镇", "再次挑战", "本次登录不在提醒框", "本次登录不在提醒确认", "金牌", "age_tips",
              "start_game"]


# guidepost: [str] = ["路标三角形", "布万家狮子头门口"]


def get_name(n: int) -> str:
    i = int(n)
    st = names.get(i)
    if st == None:
        logo.Mlog.logger.error(f"key不存在={i}")
        return None
    else:
        return st


# print(names[0])
# Set YOLOv8 to quiet mode
yolo = YOLO("best.pt", task="detect")


# yolo.predict(source="./yolo/runs/detect",save=True,verbose=False)
# yolo = YOLO("./yolo/xlc.pt", task="detect")


def get_prop(job: str) -> ([Prop], [Prop], [Prop], Prop, Prop, [Prop], [Prop], bool):
    global results
    enemys: [Prop] = []
    stuffs: [Prop] = []
    # 三角形路标
    guideposts: [Prop] = []
    icos: [Prop] = []
    exports: [Prop] = []
    # boss路标,终点引路标志
    end_guidepost: Prop = None
    player: Prop = None
    # 切换场景
    cut_room: bool = False
    #  是否通关了
    clearance: bool = False
    # 截屏
    screenshot = event.take_screenshot()
    # 通过颜色判断是否是黑屏了
    if event.is_black_screen(screenshot):
        cut_room = True

    # print(f"slssource=screen ----------", file=sys.stdout),verbose=False

        # print(f"slssource=screen ----------")conf=0.4,
    results = yolo.predict(source=screenshot, verbose=False, save=True)

    for result in results:
        for i in range(len(result)):
            p = Prop(get_name(result.boxes.cls[i]), result.boxes.xywh[i])
            for em in enemy:
                if em == p.name:
                    enemys.append(p)
            for sf in stuff:
                if sf == p.name:
                    stuffs.append(p)
            for ic in ico:
                if ic == p.name:
                    icos.append(p)

            if p.name == "出入口" or p.name == "领主入口":
                exports.append(p)
            elif p.name == "路标三角形":
                guideposts.append(p)
            elif p.name == "路标移动" or p.name == "路标领主":
                end_guidepost = p
            elif p.name == job:
                player = p
    # print(f"sls{0},xywh={0}")
    # 确保截屏图像资源被释放（假设有一个适当的释放方法）
    # screenshot.release()
    return enemys, stuffs, guideposts, end_guidepost, player, icos, exports, cut_room

# ps = get_prop("")
# for p in ps:
#     print(p)
